package com.schx.budget.service.impl;

import com.schx.budget.dto.FileUploadDTO;
import com.schx.budget.mapper.FileMsgMapper;
import com.schx.budget.pojo.FileMsg;
import com.schx.budget.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname FileServiceImpl
 * @Description TODO
 * @Date 2021/2/3 16:09
 * @Created by cyh
 */

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMsgMapper fileMsgMapper;

    @Override
    public Boolean fileUpload(FileUploadDTO fileUploadDTO) {
        File target = fileUploadDTO.getTarget();
        //初始化路径
        if(!target.getParentFile().exists()){
            target.getParentFile().mkdir();
        }
        boolean flag =false;
        Lock lock=new ReentrantLock();
        lock.lock();
        try {
            String fileName=fileUploadDTO.getSource().getOriginalFilename();

            //特殊字符转义
            fileName.replaceAll(" ", "%20");
            fileName = URLEncoder.encode(fileName, "UTF-8");

            //处理重名
            while(target.exists()){
                int cutPoint = fileName.lastIndexOf(".");
                fileName=fileName.substring(0,cutPoint)+"(1)"+fileName.substring(cutPoint,fileName.length());
                target=new File(fileUploadDTO.getPath()+fileName);
            }
            //保存文件信息
            FileMsg fileMsg = new FileMsg();
            fileMsg.setId(UUID.randomUUID().toString().replace("-", ""));
            fileMsg.setFileName(fileName);
            fileMsg.setFileSize(fileUploadDTO.getSource().getSize());
            fileMsg.setFileType(fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()));
            fileMsg.setUploadTime(fileUploadDTO.getUploadTime());
            fileMsg.setUserName(fileUploadDTO.getUsername());
            fileMsg.setPath(target.getPath());
            int rows = fileMsgMapper.insertFileMsg(fileMsg);
            //保存文件
            if (rows > 0) {
                 flag = save(fileUploadDTO.getSource(), target);
            }else{
                return false;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return flag;
    }

    @Override
    public List<FileMsg> getFileList(Integer start,Integer end, String orgid) {
        return fileMsgMapper.queryFileList(start,end,orgid);
    }

    @Override
    public List<FileMsg> queryFileListByFileName(String fileName) {
        return fileMsgMapper.queryFileListByFileName(fileName);
    }

    @Override
    public boolean deleteFile(File file, String fileName) {
        //删除信息
        int rows=fileMsgMapper.delete(fileName);
        //删除文件
        if(file.exists()&&rows>0){
            file.delete();
        }else{
            return false;
        }
        return true;
    }


    private boolean save(MultipartFile file, File tempFile){
        try(FileOutputStream fos=new FileOutputStream(tempFile);){
            InputStream is = file.getInputStream();
            int len=0;
            byte[] bytes=new byte[8*1024];
            while((len = is.read(bytes)) != -1){
                fos.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
